package com.hckj.medical.controller;

import com.aliyun.oss.OSS;
import com.hckj.medical.utils.Code;
import com.hckj.medical.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;


@RestController
@RequestMapping("/medical")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class OssController {

    @Autowired
    private OSS ossClient;

    @PostMapping("/uploadImg")
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public R uploadImg(MultipartFile file) throws IOException {
        System.out.println(file);
        //获取文件后缀名
        String originalFilename = file.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String png = originalFilename.substring(i);

        //存储空间的名字
        String bucketName = "nillll";
        //生成新的文件名 brand/：在bucketName里面创建的分组
        String fileName = "nil/" + UUID.randomUUID().toString().substring(0, 6) + png;
        // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（fileName）。
        ossClient.putObject(bucketName, fileName, file.getInputStream());
        //文件访问地址。
        String url = "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com" + "/" + fileName;
        System.out.println("上传成功返回的：" + url);
        // 关闭OSSClient。
        ossClient.shutdown();
        return new R(Code.GET_OK,url,"添加成功");
    }
}